//
//  RCacheManager.m
//  iMoive
//
//  Created by 侯伟 on 2021/9/16.
//

#import "RCacheManager.h"
#import <SJMediaCacheServer/SJMediaCacheServer.h>
#import <SDWebImage/SDImageCache.h>
#import "RVideoObj.h"
#import "RCacheObj.h"
#import "RCacheCellObj.h"

static RCacheManager* manager = NULL;

@interface RCacheManager ()<MCSAssetExportObserver>

@property(nonatomic,strong)NSArray* cacheItems;

@end

@implementation RCacheManager

+ (instancetype)share{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [RCacheManager new];
    });
    return manager;
}

- (instancetype)init{
    self = [super init];
    if (self) {
        
    }
    return self;
}

/// 缓存大小
- (NSString*)cacheSizeStr{
    
    NSUInteger intg = [[SDImageCache sharedImageCache] totalDiskSize];
    
    NSInteger bytes = SJMediaCacheServer.shared.countOfBytesRemovableCaches;
    
    NSInteger total = intg + bytes;
    
    NSString* sizeStr = @"0";
    if(total < 1024*1024*1024){
        sizeStr = [NSString stringWithFormat:@"%.1fM",total/(1024.0*1024.0)];
    }else{
        sizeStr = [NSString stringWithFormat:@"%.1fG",total/(1024.0*1024.0*1024)];
    }
    return sizeStr;
}

/// 缓存视频
/// @param video 视频
/// @param urlObj 地址
- (void)cacheVideo:(RVideoObj*)video url:(RVideoUrlObj*)urlObj{
    
    RCacheObj* cacheObj = [RCacheObj new];
    cacheObj.url = urlObj.url_m3u8;
    cacheObj.name = [NSString stringWithFormat:@"%@ %@",video.name,urlObj.url_info];
    cacheObj.state = 0;
    cacheObj.progress = 0.0f;
    cacheObj.converImage = video.img;
    
    [[RLMRealm defaultRealm] transactionWithBlock:^{
        [[RLMRealm defaultRealm] addOrUpdateObject:cacheObj];
    }];
    
    NSURL* URL = [NSURL URLWithString:urlObj.url_m3u8];

    [SJMediaCacheServer.shared exportAssetWithURL:URL resumes:YES];
}

/// 所有的缓存
- (NSArray<RCacheObj*>*)allCacheItems{
    RLMResults* ret = [RCacheObj allObjects];
    
    NSMutableArray* objs = [NSMutableArray array];
    for (int i = 0; i < ret.count; i++) {
        [objs addObject:[ret objectAtIndex:i]];
    }
    return objs;
}

/// 所有的列表
- (NSArray<RCacheCellObj*>*)allCacheCells{
    
    NSMutableArray* cellObjs = [NSMutableArray array];
    
    NSArray* cacheObjs = [self allCacheItems];
    
    for (RCacheObj* obj in cacheObjs) {
        
        RCacheCellObj *row = [[RCacheCellObj alloc] initWithMedia:obj];
        
        [cellObjs addObject:row];
    }
    
    return cellObjs;
}

/// 删除缓存
- (void)removeCacheWithURLStr:(NSString*)urlStr{
    NSURL* url = [NSURL URLWithString:urlStr];
    
    if(!url) return;
    
    [SJMediaCacheServer.shared removeExportAssetWithURL:url];
    
    RLMResults* ret = [RCacheObj objectsWhere:@"url = %@",urlStr];
    if(ret.count){
        [[RLMRealm defaultRealm] transactionWithBlock:^{
            [[RLMRealm defaultRealm] deleteObjects:ret];
        }];
    }
}

//开始缓存
- (void)startAllCache{
    
    [Queue asyncGlobal:^{
        NSArray<id<MCSAssetExporter>> *exports = [SJMediaCacheServer.shared allExporters];
        for (id<MCSAssetExporter> export in exports) {
            [export synchronize];
            [export resume];
        }
    }];
}

- (void)stopAllCache{
    
    [Queue asyncGlobal:^{
        NSArray<id<MCSAssetExporter>> *exports = [SJMediaCacheServer.shared allExporters];
        for (id<MCSAssetExporter> export in exports) {
            [export suspend];
        }
    }];
}

- (void)removeAllCache{
    [SJMediaCacheServer.shared removeAllExportAssets];
    [SJMediaCacheServer.shared removeAllRemovableCaches];
    
    RLMResults* ret = [RCacheObj allObjects];
    if(ret.count){
        [[RLMRealm defaultRealm] transactionWithBlock:^{
            [[RLMRealm defaultRealm] deleteObjects:ret];
        }];
    }
    
    [[SDImageCache sharedImageCache] clearMemory];
    [[SDImageCache sharedImageCache] clearDiskOnCompletion:NULL];
}

@end
